package cn.tedu.bece.front.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.tedu.bece.front.common.response.JsonResult;
import cn.tedu.bece.front.common.service.SmsService;
import cn.tedu.bece.front.pojo.dto.UpdatePhoneParam;
import cn.tedu.bece.front.pojo.dto.UpdateUsernameParam;
import cn.tedu.bece.front.pojo.dto.UserLoginParam;
import cn.tedu.bece.front.pojo.dto.UserQuery;
import cn.tedu.bece.front.pojo.vo.UserVO;
import cn.tedu.bece.front.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    SmsService smsService;
    @Autowired
    UserService userService;

    @PostMapping("/loginByPhone")
    public JsonResult loginByPhone(@RequestBody UserLoginParam userLoginParam){
        log.debug("用户登录:userLoginParam={}",userLoginParam);

        smsService.check(userLoginParam.getPhone(), userLoginParam.getVerificationCode());

        UserVO userVO = userService.loginAndRegister(userLoginParam);
        return JsonResult.success(userVO);
    }

    @GetMapping("/sendVerificationCode")
    public JsonResult sendVerificationCode(@RequestParam String phone) {
        smsService.send(phone);
        return JsonResult.success();
    }

    @GetMapping("/selectById")
    public JsonResult selectUserById(UserQuery userQuery){
        log.debug("通过id查询用户：userQuery={}",userQuery);
        Integer userId = StpUtil.getLoginIdAsInt();
        userQuery.setId(userId);
        UserVO userVO = userService.selectUserById(userQuery);
        return JsonResult.success(userVO);
    }

    @PostMapping("/updateUsername")
    public JsonResult updateUsername(@RequestBody UpdateUsernameParam updateUsernameParam){
        log.debug("修改用户名：username={}",updateUsernameParam.getUsername());
        Integer userId = StpUtil.getLoginIdAsInt();
        userService.updateUsername(userId,updateUsernameParam.getUsername());
        return JsonResult.success();
    }

    @PostMapping("/updatePhone")
    public JsonResult updatePhone(@RequestBody UpdatePhoneParam updatePhoneParam){
        log.debug("修改绑定手机号：phone={}",updatePhoneParam.getPhone());
        Integer userId = StpUtil.getLoginIdAsInt();
        userService.updatePhone(userId,updatePhoneParam.getPhone());
        return JsonResult.success();
    }

    @PostMapping("/logout")
    public JsonResult logout() {
        StpUtil.logout();
        return JsonResult.success();
    }


}
